package jobs.job3.classloaderdemo.user;

import jobs.job3.classloaderdemo.client.Client;
import jobs.job3.classloaderdemo.server.standard.bean.TaskBean;
import jobs.job3.classloaderdemo.user.algorithm.OrderMergeTask;
import jobs.job3.classloaderdemo.server.util.Utils;

import java.io.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class Demo {

//    读取文件内容以字节数组返回
    public static byte[] readClassFileContent(String filename) {
        try (InputStream is = new FileInputStream(new File(filename));
             ByteArrayOutputStream outputStream = new ByteArrayOutputStream()) {
            int x;
            while ((x = is.read()) != -1) outputStream.write(x);
            return outputStream.toByteArray();
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    public static void main(String[] args) throws Exception {

//        得到一个无序数组
        int[] array = Utils.genUnorderedArray(20);
        System.out.println("待排序数组：" + Arrays.toString(array));

//        将数组元素分成两部分
        int[] left = Arrays.copyOfRange(array, 0, array.length / 2);
        int[] right = Arrays.copyOfRange(array, array.length / 2, array.length);

//        打印
        System.out.println("left: " + Arrays.toString(left));
        System.out.println("right: " + Arrays.toString(right));

//        服务器列表，由于通过zookeeper 获取服务器列表，因此不在需要静态配置
//        String[] cnHosts = {"localhost:8888", "localhost:8889"}; //"localhost:9000"

//        读取排序算法类的字节码
        byte[] sortProgram = readClassFileContent("target/classes/jobs/job3/classloaderdemo/user/algorithm/MySortTask.class");
//        读取归并算法类的字节码
        byte[] mergeProgram = readClassFileContent("target/classes/jobs/job3/classloaderdemo/user/algorithm/OrderMergeTask.class");

//        根据 类名+程序+输入 封装成 网络传输对象
        TaskBean taskBean = TaskBean.of("jobs.job3.classloaderdemo.user.algorithm.MySortTask", sortProgram, left);
        TaskBean taskBean2 =TaskBean.of("jobs.job3.classloaderdemo.user.algorithm.MySortTask", sortProgram, right);
//        放在任务列表中
        List<TaskBean> taskBeans = new ArrayList<>();
        taskBeans.add(taskBean);
        taskBeans.add(taskBean2);

//        将任务列表中所有任务计算结束后的结果聚合的任务
//       其输入为任务列表中所有任务的计算结果集合，因此暂时为null
        TaskBean reduceTask =  TaskBean.of(
                "jobs.job3.classloaderdemo.user.algorithm.OrderMergeTask",
                mergeProgram, (byte[]) null);

//        创建client对象，用于给计算节点均匀分配任务
        Client< OrderMergeTask.TwoArray, int[]> client = new Client<>();
//        将任务转发给计算节点计算，并获取返回结果
        int[] sortedResult = client.execute(taskBeans, list -> new OrderMergeTask.TwoArray(list.get(0), list.get(1)), reduceTask);
        System.out.println("全排序后的结果：" + Arrays.toString(sortedResult));
    }

}

